/**
 * Filename: AlbumStatusActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/3 10:52
 */
package com.github.postsanf.yinian.activity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.NewsFragmentAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNAlbumResponse;
import com.github.postsanf.yinian.fragment.AlbumIntroFragment;
import com.github.postsanf.yinian.fragment.AlbumMemberFragment;
import com.github.postsanf.yinian.fragment.AlbumStatusFragment;
import com.github.postsanf.yinian.fragment.AlbumWallFragment;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class AlbumStatusActivity extends BaseActivity implements ISkinUpdate {
    private Toolbar mToolbar;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private YNAlbum curAlbum;
    public AppBarLayout mAppBar;
    private RelativeLayout rl_official_album_invite;
    private TextView tv_invite;
    private boolean isFromHome = false;
    private CollapsingToolbarLayout collapsingToolbar;
    private SimpleDraweeView mAlbumBG;
    private MenuItem action_album_manage;
    private Resources mResource;
    private TextView tv_photos;
    private TextView tv_users;
    private FloatingActionButton fab_publish_status;
    public static boolean whiteblack = false;
    private ImageView tabiv1, tabiv2, tabiv3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_album_status);
        BaseApplication.getInstance().mActivitys.add(this);
        registerBoradcastReceiver();
        curAlbum = YNSingleton.getInstance().getCurAlbum();
        application.setCurgimid(curAlbum.getGimid());
        int nowHour = new Date().getHours();
        if (nowHour > 6 && nowHour <= 18) {
            whiteblack = true;
        } else if (nowHour > 18 || nowHour < 6) {
            whiteblack = false;
        }
        try {
            isFromHome = getIntent().getBooleanExtra(ACTIONs.aAddData, false);
        } catch (NullPointerException e) {
            isFromHome = false;
        }
        boolean isNew = getIntent().getBooleanExtra(CommonConstants.ISNEW, false);
        if (isNew) {
            Intent intent2Manage = new Intent(this, LocalManageActivity.class);
            intent2Manage.putExtra(CommonConstants.YNGROUPID, application.getCurGid());
            startActivity(intent2Manage);
        }
        initView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        if (outState != null) {
            String FRAGMENTS_TAG = "android:support:fragments";
            // remove掉保存的Fragment
            outState.remove(FRAGMENTS_TAG);
        }
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.album_status_toolbar);
        setSupportActionBar(mToolbar);
        fab_publish_status = (FloatingActionButton) findViewById(R.id.fab_publish_status);
        fab_publish_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent2Activity(AlbumStatusIntentActivity.class);
            }
        });
        rl_official_album_invite = (RelativeLayout) findViewById(R.id.rl_official_album_invite);
        tv_invite = (TextView) findViewById(R.id.tv_invite_into_album);
        if (!StringUtils.isEmpty(curAlbum.getGtype())) {
            tv_invite.setText(StringUtils.getCateByType(curAlbum.getGtype()));
        }
        rl_official_album_invite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AlbumStatusActivity.this, InviteChooseActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, YNSingleton.getInstance().getCurAlbum());
                startActivity(intent);
            }
        });
        mAppBar = (AppBarLayout) findViewById(R.id.status_appbar);
        if (!isFromHome && YNSingleton.getInstance().getCurAlbum().getIsInAlbum() == 0) {
            fab_publish_status.setVisibility(View.GONE);
            rl_official_album_invite.setVisibility(View.VISIBLE);
        } else {
            fab_publish_status.setVisibility(View.VISIBLE);
            rl_official_album_invite.setVisibility(View.GONE);
        }
        collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_status_toolbar);
        collapsingToolbar.setTitle(curAlbum.getGname());
        mAlbumBG = (SimpleDraweeView) findViewById(R.id.iv_album_top);
        updatebg();
        tv_photos = (TextView) findViewById(R.id.tv_album_top_photos);
        tv_users = (TextView) findViewById(R.id.tv_album_top_users);
        tv_photos.setText(String.valueOf(curAlbum.getGpicnum()));
        tv_users.setText(curAlbum.getGnum());
        mViewPager = (ViewPager) findViewById(R.id.vp_status_viewpager);
        setupViewPager();
    }

    // 加入官方相册
    private void doJoinOfficial() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_INVITE_CODE, YNSingleton.getInstance().getCurAlbum().getGinvite());
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynApplyGroup))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumResponse resOfficial = gson.fromJson(s, YNAlbumResponse.class);
                        if (resOfficial != null && ReqUtils.isSuccessTwo(resOfficial.getCode()) && resOfficial.getData().size() > 0) {
                            sendBroadcast(new Intent(ACTIONs.actionUpJoinState));
                            rl_official_album_invite.setVisibility(View.GONE);
                            YNSingleton.getInstance().getCurAlbum().setIsInAlbum(1);
                            // 显示投稿按钮
                            fab_publish_status.setVisibility(View.VISIBLE);
                            // 通知进入已进入相册
                            Intent mIntent = new Intent(ACTIONs.actionJoinState);
                            sendBroadcast(mIntent);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    public void showActionButton(boolean flag) {
        fab_publish_status.setVisibility(flag ? View.VISIBLE : View.GONE);
    }


    // 初始化切换
    private void setupViewPager() {
        LayoutInflater mLayoutInflater = android.view.LayoutInflater.from(AlbumStatusActivity.this);
        mTabLayout = (TabLayout) findViewById(R.id.tl_status_tabs);
        List<String> titles = new ArrayList<>();
        titles.add("动态");
        titles.add("照片墙");
        if (curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.gfxc)) {
            titles.add("介绍");
        } else {
            titles.add("成员");
        }
        List<View> Views = new ArrayList<>();
        View tabview1 = mLayoutInflater.inflate(R.layout.tabalbumstatus_view1, null);
        tabiv1 = (ImageView) tabview1.findViewById(R.id.album_tab1_iv);
        tabiv1.setImageResource(R.drawable.album_tab_p1_green);
        Views.add(tabview1);
        View tabview2 = mLayoutInflater.inflate(R.layout.tabalbumstatus_view2, null);
        tabiv2 = (ImageView) tabview2.findViewById(R.id.album_tab2_iv);
        Views.add(tabview2);
        View tabview3 = mLayoutInflater.inflate(R.layout.tabalbumstatus_view3, null);
        tabiv3 = (ImageView) tabview3.findViewById(R.id.album_tab3_iv);
        TextView tabtx3 = (TextView) tabview3.findViewById(R.id.album_tab3_title);
        if (curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.gfxc) || curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.xyxc)) {
            tabtx3.setText("介绍");
        } else {
            tabtx3.setText("成员");
        }
        Views.add(tabview3);
//        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(0)));
//        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(1)));
//        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(2)));
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new AlbumStatusFragment());
        fragments.add(new AlbumWallFragment());
        if (curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.gfxc) || curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.xyxc)) {
            // 加入官方相册
            doJoinOfficial();
            fragments.add(new AlbumIntroFragment());
        } else {
            fragments.add(new AlbumMemberFragment());
        }
        NewsFragmentAdapter adapter = new NewsFragmentAdapter(getSupportFragmentManager(), fragments, titles);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(3);
        mTabLayout.setupWithViewPager(mViewPager);
        // mTabLayout.setTabsFromPagerAdapter(adapter);
        mTabLayout.getTabAt(0).setCustomView(Views.get(0));
        mTabLayout.getTabAt(1).setCustomView(Views.get(1));
        mTabLayout.getTabAt(2).setCustomView(Views.get(2));
        if (!isFromHome && YNSingleton.getInstance().getCurAlbum().getIsInAlbum() == 0) {
            // 跳转至介绍页面
            mViewPager.setCurrentItem(2);
            fab_publish_status.setVisibility(View.GONE);
            tabiv3.setImageResource(R.drawable.album_tab_p3_green);
            tabiv1.setImageResource(R.drawable.album_tab_p1_white);
            tabiv2.setImageResource(R.drawable.album_tab_p2_white);
        }

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        fab_publish_status.setVisibility(View.VISIBLE);
                        rl_official_album_invite.setVisibility(View.GONE);
                        tabiv1.setImageResource(R.drawable.album_tab_p1_green);
                        tabiv2.setImageResource(R.drawable.album_tab_p2_white);
                        tabiv3.setImageResource(R.drawable.album_tab_p3_white);
                        break;
                    case 1:
                        fab_publish_status.setVisibility(View.GONE);
                        rl_official_album_invite.setVisibility(View.GONE);
                        tabiv2.setImageResource(R.drawable.album_tab_p2_green);
                        tabiv1.setImageResource(R.drawable.album_tab_p1_white);
                        tabiv3.setImageResource(R.drawable.album_tab_p3_white);
                        break;
                    case 2:
                        fab_publish_status.setVisibility(View.GONE);
                        if (!(curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.gfxc) || curAlbum.getGtype() != null && curAlbum.getGtype().equals(CommonConstants.xyxc))) {
                            rl_official_album_invite.setVisibility(View.VISIBLE);
                        }
                        tabiv3.setImageResource(R.drawable.album_tab_p3_green);
                        tabiv1.setImageResource(R.drawable.album_tab_p1_white);
                        tabiv2.setImageResource(R.drawable.album_tab_p2_white);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_status, menu);
        action_album_manage = menu.findItem(R.id.action_album_manage);
        if (mResource != null) {
            action_album_manage.setIcon(mResource.getDrawable(mResource.getIdentifier("ic_manage", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_album_manage:
                if (!isFromHome && YNSingleton.getInstance().getCurAlbum().getIsInAlbum() == 0) {
                    return true;
                }
                Intent intent = new Intent(this, AlbumManageActivity2.class);
                startActivityForResult(intent, CommonConstants.REQ_GROUP_MANAGE);
                break;
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updatebg() {
        String urls = (curAlbum == null || curAlbum.getGpic() == null) ? "" : curAlbum.getGpic();
        String paths = YNUrlHelper.getStatusBlur(this, urls);
        Uri uri = Uri.parse(paths);
        ImageOptHelper.showFrescoBlur(uri, mAlbumBG, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonConstants.REQ_GROUP_MANAGE && resultCode == RESULT_OK) {
            int tag = data.getIntExtra(CommonConstants.REQ_CODE, 0);
            switch (tag) {
                //  删除该组关闭页面并更新主页信息
                case 1:
                    Intent upIntent = new Intent(ACTIONs.actionAlbumItem);
                    upIntent.putExtra(ACTIONs.aAlbumItem, curAlbum);
                    upIntent.putExtra(ACTIONs.IsAdd, false);
                    sendBroadcast(upIntent);
                    finish();
                    break;
            }
        }
    }

    // 分析并执行动作
    BroadcastReceiver mAlbumBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                //　更新组名
                case ACTIONs.actionAlertGName:
                    curAlbum.setGname(YNSingleton.getInstance().getCurAlbum().getGname());
                    collapsingToolbar.setTitle(YNSingleton.getInstance().getCurAlbum().getGname());
                    break;
                //　更新组背景
                case ACTIONs.actionAlertGPic:
                    curAlbum.setGpic(YNSingleton.getInstance().getCurAlbum().getGpic());
                    updatebg();
                    break;
                case ACTIONs.actionToTimeCardDetail:
                    context.startActivity(new Intent(context, TimeCardDetailActivity.class).putExtra("TimeCard", "TimeCard"));
                    // overridePendingTransition(R.anim.slide_center_out, R.anim.slide_center_out);
                    break;
            }
        }
    };

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_OK, new Intent());
    }

    // 注册接收者
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionAlertGName);
        myIntentFilter.addAction(ACTIONs.actionAlertGPic);
        myIntentFilter.addAction(ACTIONs.actionToTimeCardDetail);
        registerReceiver(mAlbumBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onDestroy() {
        BaseApplication.getInstance().mActivitys.remove(this);
        unregisterReceiver(mAlbumBroadcastReceiver);
        super.onDestroy();
        application.setCurgimid(null);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                collapsingToolbar.setCollapsedTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                collapsingToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                collapsingToolbar.setContentScrimColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mTabLayout.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    TextView tv = new TextView(this);
                    tv.setText(mTabLayout.getTabAt(i).getText());
                    tv.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                    mTabLayout.getTabAt(i).setCustomView(null);
                    mTabLayout.getTabAt(i).setCustomView(tv);
                }

                fab_publish_status.setBackgroundTintList(mResource.getColorStateList(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                fab_publish_status.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("ic_mode_edit_white_48dp", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                rl_official_album_invite.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                tv_invite.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "openSpaceDetail_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}
